<template>
  <div>
    <breadcrumb>
      <span slot="first">首页</span>
      <span slot="second">商品管理</span>
      <span slot="third">添加商品</span>
    </breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex * 1" align-center finish-status="success">
        <el-step title="基本信息" icon="el-icon-edit"></el-step>
        <el-step title="商品参数" icon="el-icon-s-order"></el-step>
        <el-step title="商品属性" icon="el-icon-document"></el-step>
        <el-step title="商品图片" icon="el-icon-picture"></el-step>
        <el-step title="商品内容" icon="el-icon-files"></el-step>
        <el-step title="完成" icon="el-icon-circle-check"></el-step>
      </el-steps>
      <!-- tab栏 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRefs" label-position="top">
        <el-tabs @tab-click="tabClick" tab-position="left" v-model="activeIndex" :before-leave="beforeTabLeave">
          <!-- 1. -->
          <el-tab-pane label="基本信息" name="0">
            <!-- 商品名称 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <!-- 商品价格 -->
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <!-- 商品重量 -->
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <!-- 商品数量 -->
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 商品分类 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="categoryList" :props="addProps" @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 2. -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyDataList" :key="item.attr_id" :label="item.attr_name">
              <!-- 多选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 3. -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyDataList" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 4. -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload action="http://127.0.0.1:8888/api/private/v1/upload" :on-preview="handlePreview"
              :on-remove="handleRemove" list-type="picture" :headers="uploadHeaders" :on-success="imgUploadSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 5. -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="addition">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewImagePath" alt="" class="previewImage">
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/common/Breadcrumb.vue'
import { request } from '@/network/request.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
export default {
  name: "Add",
  components: { Breadcrumb, quillEditor },
  data() {
    return {
      activeIndex: '0',
      // 增加商品表单数据绑定
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 表单校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ]
      },
      // 级联选择框配置
      addProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 分类列表
      categoryList: [],
      // 动态参数列表
      manyDataList: [],
      // 静态属性列表
      onlyDataList: [],
      // 图片上传请求头
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览url
      previewImagePath: '',
      previewVisible: false
    }
  },
  methods: {
    // 获取所有分类数据
    async getCategoryList() {
      const { data: res } = await request("/categories")
      if (res.meta.status !== 200) return this.$message.error("获取分类数据失败")
      this.categoryList = res.data
    },
    // 级联选择框改变触发
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
      console.log(this.addForm.goods_cat);
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length === 0) {
        this.$message.info("请先选择分类")
        return false
      }
    },
    tabClick() {
      switch (
      this.activeIndex
      ) {
        case '1':
          this.getManyData()
          break
        case '2':
          this.getOnlyData()
          break
      }
    },
    async getManyData() {
      const { data: res } = await request({
        url: `categories/${this.categoryId}/attributes`,
        params: { sel: 'many' }
      })
      if (res.meta.status !== 200) return this.$message.error("获取分类数据失败")
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(',')
      });
      this.manyDataList = res.data
      console.log(this.manyDataList);
    },
    async getOnlyData() {
      const { data: res } = await request({
        url: `categories/${this.categoryId}/attributes`,
        params: { sel: 'only' }
      })
      if (res.meta.status !== 200) return this.$message.error("获取分类数据失败")
      this.onlyDataList = res.data
    },
    // 图片预览触发
    handlePreview(file) {
      this.previewImagePath = file.response.data.url
      this.previewVisible = true
    },
    // 图片删除触发
    handleRemove(file) {
      console.log(file);
      const path = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(item => item.pic === path)
      this.addForm.pics.splice(index, 1)
    },
    // 图片上传成功钩子函数
    imgUploadSuccess(res) {
      this.addForm.pics.push({
        pic: res.data.tmp_path
      })
    },
    // 添加商品
    addition() {
      // 进行表单预验证
      this.$refs.addFormRefs.validate(async valid => {
        if (!valid) return this.$message.warning("请填写必填项")
        // 验证成功
        // 对addForm进行深拷贝，原因是提交的表单中的goods_cat需要字符串，而级联选择框双向绑定的是数组
        const form = JSON.parse(JSON.stringify(this.addForm))
        // 对goods_cat进行处理
        form.goods_cat = form.goods_cat.join(",")
        // 对动态参数进行处理
        this.manyDataList.forEach(item => {
          this.addForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          })
        })
        // 对静态属性进行处理
        this.onlyDataList.forEach(item => {
          this.addForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        form.attrs = this.addForm.attrs
        // 发送网络请求
        const {data: res} = await request({
          url: '/goods',
          method: 'post',
          data: form 
        })
        if (res.meta.status !== 201) return this.$message.error("创建商品失败")
        this.$message.success("创建商品成功")
        this.$router.replace("/goods")
      })
    }
  },
  created() {
    this.getCategoryList()
  },
  computed: {
    // 分类id
    categoryId() {
      return this.addForm.goods_cat.length === 0 ? null : this.addForm.goods_cat[2]
    }
  },
}
</script>

<style lang='less' scoped>
.el-steps {
  margin: 18px 0;
}

.el-checkbox {
  margin-right: 10px;
  margin-bottom: 5px;
}

.previewImage {
  width: 100%;
}

.btnAdd {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  margin: 15px 0;
}
</style>